var app = getApp();
var WxParse = require('../../../lib/wxParse/wxParse.js');
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const user = require('../../../services/user.js');
const ctx = wx.createCanvasContext('shareCanvas');

Page({
    data: {
        items: [
            {name: '月结铺货', value: 0, checked: 'true'},
            {name: '月结换货', value: 1},
            {name: '直接购买', value: 2}
        ],
        radioStatus:0,
        backTop:30,
        latitude:'',
        longitude:'',
        addressInfo:{},
        timer:null,
        orderGoods:[],
        Height: 0,
        timeLeft:0,
        scale: 17,
        priceLeft:'0',
        priceRight:'00',
        latitude: "",
        longitude: "",
        markers: [],
        circles: [],
        timeTo:0,
        id: 0,
        goods: {},
        retailPrice: '',
        gallery: [],
        attribute: [],
        showCanvas:false,
        issueList: [],
        comment: [],
        wxaCodeImg:null,
        brand: {},
        specificationList: [],
        productList: [],
        relatedGoods: [],
        cartGoodsCount: 1,
        userHasCollect: 0,
        btnAddSlide:false,
        number: 1,
        checkedSpecText: '请选择规格',
        openAttr: false,
        indexImg:"http://booking-prod.oss-cn-shenzhen.aliyuncs.com/tata/icon_home.png",
        picUrl: null,
    },
    onPullDownRefresh: function () {
        wx.stopPullDownRefresh();
    },
    onShareAppMessage: function() {
        return {
            title: this.data.goods.name,
            desc: this.data.goods.goods_brief,
            path: '/pages/goods/goods?id=' + this.data.goods.id + '&recommend_id=' + wx.getStorageSync('userInfo').id
        }
    },
    goback(){
        wx.navigateBack();
    },
    radioChange: function(e){
        this.setData({
            radioStatus: e.detail.value
        })
    },
    changeAddSlide: function() {
        if(this.data.btnAddSlide){
            this.setData({
                btnAddSlide:false
            })
        }else{
            this.setData({
                btnAddSlide:true
            })
        }
    },
    getGoodsInfo: function() {
        let that = this;
        wx.showLoading({
          title: '加载中...',
        })
        util.request(api.commodityDetail, { commodityId: that.data.id },'get').then(function(res) {
            if (res.code == 200) {
                wx.hideLoading()
                that.setData({
                    goods:res.result,
                    picUrl:res.result.commodityAlbumList[0].poster,
                    gallery:res.result.commodityAlbumList,
                })
                WxParse.wxParse('goodsDetail', 'html', res.result.detail, that);

            }
        });

    },
    //显示对话框
    showModal: function() {
        // 显示遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
            openAttr: true
        })
        setTimeout(function() {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export()
            })
        }.bind(this), 200)
    },

    //隐藏对话框
    hideModal: function() {
        // 隐藏遮罩层
        var animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        })
        this.animation = animation
        animation.translateY(300).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function() {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                openAttr: false,
                showCanvas:false,
            })
        }.bind(this), 200)
    },
    onLoad: function(options) {
        
        // 页面初始化 options为页面跳转所带来的参数
        try {
            wx.removeStorageSync('couponId')
            let couponId = wx.getStorageSync('couponId');
        } catch (e) {
            // Do something when catch error
        }
        let link = decodeURIComponent(options.q);

        if(!!options.id){
            this.setData({
                id: parseInt(options.id)
                // id: 1181000
            });
        }else if(link){
            let paramArr = link.split('=');
            this.setData({
                id: parseInt(paramArr[1])
                // id: 1181000
            });
        }

        if (!!options.recommend_id) {
            wx.setStorageSync('recommendId', options.recommend_id)
        }
        var that = this;
        this.getGoodsInfo();
        //this.getCartNum();
        // this.getWxaCodeUnlimit();
        //this.getAddressInfoList();

    },
    onReady: function() {
        // 页面渲染完成

    },
    /* getCartNum(){
        let _this = this;
        util.request(api.cartUrl.cartList).then(function(res) {
            if (res.code == 200) {
                _this.setData({
                    cartGoodsCount: res.result.count
                });

            }
        });
    }, */
    onShow: function() {
        this.setData({
            backTop: app.globalData.navHeight-38
          });
        let userInfo = wx.getStorageSync('userInfo');
        let token = wx.getStorageSync('token');
        if (userInfo && token) {
            app.globalData.userInfo = userInfo;
            app.globalData.token = token;
        }
        // 页面显示
        this.data.timer = setInterval(() =>{ //注意箭头函数！！
            this.setData({
              timeLeft: util.getTimeLeft(this.data.timeTo)//使用了util.getTimeLeft
            });
            if (this.data.timeLeft == 0) {
              clearInterval(this.data.timer);
            }
          }, 1000);

    },
    onHide: function() {
        // 页面隐藏

    },
    onUnload: function() {
        // 页面关闭

    },
    switchAttrPop: function() {
        if (this.data.openAttr == false) {
            this.setData({
                openAttr: !this.data.openAttr,
            });
        }
    },
    closeAttrOrCollect: function() {
        let that = this;
        if (this.data.openAttr) {
            this.setData({
                openAttr: false,
            });
            if (that.data.userHasCollect == 1) {
                that.setData({
                    'collectClass': 'collectIcon'
                });
            } else {
                that.setData({
                    'collectClass': 'noCollectIcon'
                });
            }
        } else {
            //添加或是取消收藏
            util.request(api.CollectAddOrDelete, { typeId: 0, valueId: this.data.id }, "POST")
                .then(function(res) {
                    let _res = res;
                    if (_res.errno == 0) {
                        if (_res.data.type == 'add') {
                            that.setData({
                                'collectClass': 'collectIcon'
                            });
                        } else {
                            that.setData({
                                'collectClass': 'noCollectIcon'
                            });
                        }

                    } else {
                        wx.showToast({
                            image: '/static/images/icon_error.png',
                            title: _res.errmsg,
                            mask: true
                        });
                    }

                });
        }

    },
    openCartPage: function() {
        wx.switchTab({
            url: '/pages/cart/cart',
        });
    },
    nowBuy: function() {
        this.addToCart(1);

    },
    checkoutOrder: function () {
        if(!app.globalData.userInfo || !app.globalData.userInfo.phone){
            this.goLogin();
            return ;
        }
        
        wx.setStorageSync("orderGoodsList", this.data.orderGoods);
        wx.navigateTo({
            url: "/pages/orderPay/orderPay",
        })
    },
    goLogin() {
      
        wx.navigateTo({
            url: '/pages/authorized/index'
        })
    },
    addToCart: function(nowBuy) {
        var that = this;
        if (this.data.openAttr == false) {
            //打开规格选择窗口
            this.showModal();
        
        } else {
        
            var cartAddPram = {
                commodityId: this.data.goods.commodityId,
                quantity: this.data.number,
            }
    
                if(!app.globalData.userInfo || !app.globalData.userInfo.phone){
                    this.goLogin();
                  }
                let orderGoodsList = {
                    activity: true,
                    commodityId: that.data.goods.commodityId,
                    markingPrice: that.data.goods.markingPrice,
                    name: that.data.goods.name,
                    poster: that.data.goods.commodityAlbumList[0].poster,
                    quantity: that.data.number,
                    savingPrice: that.data.goods.markingPrice - that.data.goods.wholesalerPrice,
                    sellingPrice: that.data.goods.sellingPrice,
                    wholesalerPrice: that.data.goods.wholesalerPrice,
                    payType:that.data.radioStatus
                }
                console.log(orderGoodsList)
                wx.setStorageSync("orderGoodsList", orderGoodsList);
                wx.navigateTo({
                    url: '/pages/wholesalers/orderPay/orderPay'
                })
            

            
            
        }

    },
    cutNumber: function() {
        this.setData({
            number: (this.data.number - 1 > 1) ? this.data.number - 1 : 1
        });
    },
    addNumber: function() {
        this.setData({
            number: this.data.number + 1
        });
    }
})
